#ifndef UNIFIEDEXPORTSTATEMANAGER_H
#define UNIFIEDEXPORTSTATEMANAGER_H

#include <QObject>
#include <QTimer>
#include <QDateTime>
#include <QString>
#include <QStringList>
#include <QList>
#include <QFileInfo>
#include <QDebug>
#include <QStateMachine>
#include <QState>

/**
 * UnifiedExportStateManager - 统一导出状态管理器
 * 
 * 基于状态机模式管理导出状态，提供清晰的状态转换和事件处理
 * 支持文件状态验证、导出进度跟踪、错误处理和恢复
 */
class UnifiedExportStateManager : public QObject
{
    Q_OBJECT

public:
    // 导出状态枚举
    enum class ExportState {
        Idle,           // 空闲状态
        Ready,          // 准备就绪（有文件可导出）
        Exporting,      // 导出进行中
        Completed,      // 导出完成
        Failed,         // 导出失败
        Cancelled       // 导出取消
    };
    
    // 文件状态枚举
    enum class FileState {
        NoFiles,        // 无文件
        HasFiles,       // 有文件
        InvalidFiles,   // 文件无效
        ProcessingFiles // 处理文件中
    };
    
    // 文件类型枚举
    enum class FileType {
        Unknown,
        PDF,
        Image,
        Text
    };
    
    // 错误严重程度枚举
    enum class ErrorSeverity {
        Info,       // 信息提示
        Warning,    // 警告
        Error,      // 错误
        Critical    // 严重错误
    };
    
    // 导出上下文结构
    struct ExportContext {
        ExportState state = ExportState::Idle;
        FileState fileState = FileState::NoFiles;
        int totalFiles = 0;
        int completedFiles = 0;
        QString currentStatus;
        QString errorMessage;
        QDateTime startTime;
        QDateTime endTime;
        QStringList supportedFormats = {"pdf", "jpg", "jpeg", "png", "bmp", "tiff"};
        
        // 状态查询方法
        bool canExport() const {
            return state == ExportState::Ready && fileState == FileState::HasFiles;
        }
        
        bool isExporting() const {
            return state == ExportState::Exporting;
        }
        
        bool isCompleted() const {
            return state == ExportState::Completed;
        }
        
        bool isFailed() const {
            return state == ExportState::Failed;
        }
        
        bool isCancelled() const {
            return state == ExportState::Cancelled;
        }
        
        double progressPercentage() const {
            return totalFiles > 0 ? (double)completedFiles / totalFiles * 100.0 : 0.0;
        }
        
        QString stateDescription() const {
            switch (state) {
                case ExportState::Idle: return "空闲";
                case ExportState::Ready: return "准备就绪";
                case ExportState::Exporting: return "导出中";
                case ExportState::Completed: return "导出完成";
                case ExportState::Failed: return "导出失败";
                case ExportState::Cancelled: return "导出取消";
                default: return "未知状态";
            }
        }
    };
    
    // 文件验证结果结构
    struct FileValidationResult {
        bool isValid = false;
        QString error;
        FileType type = FileType::Unknown;
        qint64 size = 0;
        QDateTime lastModified;
        QString suggestedAction;
        
        static FileValidationResult createError(const QString& errorMsg) {
            FileValidationResult result;
            result.isValid = false;
            result.error = errorMsg;
            return result;
        }
        
        static FileValidationResult createSuccess(FileType fileType, qint64 fileSize, QDateTime modified) {
            FileValidationResult result;
            result.isValid = true;
            result.type = fileType;
            result.size = fileSize;
            result.lastModified = modified;
            return result;
        }
    };
    
    // 导出错误结构
    struct ExportError {
        ErrorSeverity severity = ErrorSeverity::Error;
        QString code;
        QString message;
        QString suggestion;
        bool canRetry = false;
        
        static ExportError createError(const QString& code, const QString& message, 
                                     const QString& suggestion = "", bool retry = false) {
            ExportError error;
            error.code = code;
            error.message = message;
            error.suggestion = suggestion;
            error.canRetry = retry;
            return error;
        }
    };

public:
    explicit UnifiedExportStateManager(QObject* parent = nullptr);
    ~UnifiedExportStateManager();
    
    // 状态查询
    ExportState currentState() const { return m_context.state; }
    FileState currentFileState() const { return m_context.fileState; }
    const ExportContext& context() const { return m_context; }
    bool canExport() const { return m_context.canExport(); }
    bool isExporting() const { return m_context.isExporting(); }
    
    // 文件状态管理
    void setFiles(const QStringList& filePaths);
    void addFile(const QString& filePath);
    void removeFile(const QString& filePath);
    void clearFiles();
    
    // 导出控制
    void startExport();
    void updateProgress(int completed, int total, const QString& status = "");
    void completeExport();
    void failExport(const QString& error);
    void cancelExport();
    
    // 配置
    void setSupportedFormats(const QStringList& formats);
    void setCompletionDelay(int delayMs);
    void setHealthCheckInterval(int intervalMs);
    
    // 错误处理
    ExportError analyzeError(const QString& errorMessage) const;
    void handleError(const ExportError& error);

signals:
    // 状态变化信号
    void stateChanged(ExportState newState, ExportState oldState);
    void fileStateChanged(FileState newState);
    void contextChanged(const ExportContext& context);
    
    // 导出进度信号
    void exportProgressChanged(int completed, int total, const QString& status);
    void exportStarted(int totalFiles);
    void exportCompleted();
    void exportFailed(const QString& error);
    void exportCancelled();
    
    // 文件状态信号
    void filesValidated(const QList<FileValidationResult>& results);
    void fileValidationFailed(const QString& filePath, const QString& error);
    
    // 错误处理信号
    void errorOccurred(const ExportError& error);
    void retryRequested();

private slots:
    void onStateMachineStateChanged();
    void onHealthCheckTimeout();
    void onCompletionTimeout();

private:
    // 状态机设置
    void setupStateMachine();
    void createStates();
    void createTransitions();
    
    // 文件验证
    FileValidationResult validateFile(const QString& filePath) const;
    FileType detectFileType(const QString& filePath) const;
    bool isFileSupported(const QString& filePath) const;
    
    // 状态更新
    void updateState(ExportState newState);
    void updateFileState(FileState newState);
    void updateContext();
    
    // 内部方法
    void logStateChange(ExportState from, ExportState to);
    void emitStateChangeSignals(ExportState newState, ExportState oldState);

private:
    // 状态机
    QStateMachine* m_stateMachine;
    QState* m_idleState;
    QState* m_readyState;
    QState* m_exportingState;
    QState* m_completedState;
    QState* m_failedState;
    QState* m_cancelledState;
    
    // 上下文和配置
    ExportContext m_context;
    QStringList m_filePaths;
    QTimer* m_healthCheckTimer;
    QTimer* m_completionTimer;
    
    // 配置
    int m_completionDelayMs = 2000;
    int m_healthCheckIntervalMs = 1000;
    QStringList m_supportedFormats;
    
    // 状态跟踪
    ExportState m_previousState = ExportState::Idle;
    FileState m_previousFileState = FileState::NoFiles;
};

#endif // UNIFIEDEXPORTSTATEMANAGER_H
